package thread.syn;

import java.util.concurrent.locks.ReentrantLock;

//测试Lock锁
public class TestLock {
    public static void main(String[] args) {
        TLock tLock = new TLock();
        new Thread(tLock,"x").start();
        new Thread(tLock,"y").start();
        new Thread(tLock,"z").start();
    }
}

class TLock implements Runnable{

    int ticket = 10;
    boolean flag = true;

    //定义可重用锁
    private final ReentrantLock reentrantLock = new ReentrantLock();

    @Override
    public void run() {
        while (flag){
            try {
                reentrantLock.lock();
                buy();
            }finally {
                reentrantLock.unlock();
            }
        }
    }

    private void buy() {
        if(ticket <= 0 ){
            flag = false;
            return;
        }

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + ":" +ticket--);
    }


}
